﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;

namespace WordpressDemo.Models
{
    /// <summary>Filter setting the identity.</summary>
    public class IdentityFilterAttribute : ActionFilterAttribute
    {
        private const string COOKIE_NAME = "identity";
        private static readonly string[] NO_ROLES = new string[0];

        /// <summary>Sets the identity of the user to the response cookie.</summary>
        /// <param name="response"></param>
        /// <param name="identity"></param>
        public static void SetIdentity(HttpResponseBase response, IdentityModel identity)
        {
            if (response == null)
            {
                throw new ArgumentNullException("context");
            }
            if (identity == null)
            {
                throw new ArgumentNullException("identity");
            }

            var json = identity.ToJson();
            var cookie = new HttpCookie(COOKIE_NAME, json);

            cookie.Expires = DateTime.Now.Add(TimeSpan.FromHours(1));
            response.Cookies.Add(cookie);
        }

        /// <summary>Called when the action must execute.</summary>
        /// <param name="filterContext"></param>
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var cookie = filterContext.RequestContext.HttpContext.Request.Cookies[COOKIE_NAME];

            if (cookie != null)
            {
                try
                {
                    var digest = cookie.Value;
                    var identity = IdentityModel.ToModel(digest);

                    //  Attach identity
                    filterContext.HttpContext.User = new GenericPrincipal(identity, NO_ROLES);
                }
                catch { }
            }
        }
    }
}